<!--
 * Description: SsCostPool
 * Company: 联宝（合肥）电子科技有限公司
 * Author: Qiuxue.Wu
 * Date: 2020/10/15 15:26
-->

<template>
  <BaseWrap>
    <!-- 查询条件 -->
    <BaseFunc
      :is-requesting="isRequesting"
      :query-form="queryForm"
      :visible.sync="advanceOptionDrawer"
      @query="query"
    >
      <!-- 按钮 -->
      <template slot="btn">
        <el-button
          v-if="$hasPer('add')"
          class="btn-custom"
          icon="el-icon-circle-plus-outline"
          plain
          size="mini"
          type="primary"
          @click="addDialogVisible = true"
        >
          {{ $t('button.add') }}
        </el-button>
      </template>

      <!-- 按钮 -->
      <template slot="btn-middle">
        <el-button
          class="btn-custom"
          icon="el-icon-download"
          plain
          size="mini"
          type="primary"
          @click="rowDown"
        >
          {{ '下载模板' }}
        </el-button>

        <el-button
          class="btn-custom"
          icon="el-icon-upload2"
          plain
          size="mini"
          type="primary"
          @click="uploadFile"
        >
          {{ '上传数据' }}
        </el-button>

        <input ref="inputfile" class="upload" type="file" @change="inputfileChange" />
      </template>

      <!--抽屉内部查询表单-->
      <template>
        <el-form class="g-advance-drawer-form" label-width="100px" :model="queryForm" size="medium">
          <el-row>
            <!--料号-->
            <el-col :span="6">
              <el-form-item :label="$t('Pool.material')">
                <el-input v-model="queryForm.material" clearable />
              </el-form-item>
            </el-col>

            <!--料件描述-->
            <el-col :span="6">
              <el-form-item :label="$t('Pool.materialDescription')">
                <el-input v-model="queryForm.materialDescription" clearable />
              </el-form-item>
            </el-col>

            <!--料件分组-->
            <el-col :span="6">
              <el-form-item :label="$t('Pool.materialGroup')">
                <el-input v-model="queryForm.materialGroup" clearable />
              </el-form-item>
            </el-col>

            <!--Source Type-->
            <el-col :span="6">
              <el-form-item :label="$t('Pool.sourceType')">
                <el-input v-model="queryForm.sourceType" clearable />
              </el-form-item>
            </el-col>

            <!--Tower-->
            <el-col :span="6">
              <el-form-item :label="$t('Pool.tower')">
                <el-input v-model="queryForm.tower" clearable />
              </el-form-item>
            </el-col>

            <!--ProjectId-->
            <el-col :span="6">
              <el-form-item :label="$t('Pool.projectId')">
                <el-input v-model="queryForm.projectId" clearable />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </template>
    </BaseFunc>

    <!--数据表格-->
    <BaseTable
      :is-requesting="isRequesting"
      :page-number.sync="pageNumber"
      :page-size.sync="pageSize"
      :table-data="tableData"
      :total="total"
      @query="query"
    >
      <template slot="header">
        <!--序号列-->
        <el-table-column align="center" fixed :label="$t('table.NO')" min-width="50px">
          <template slot-scope="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
      </template>

      <!--专案编号-->
      <el-table-column
        align="center"
        :label="$t('Pool.projectId')"
        min-width="250px"
        prop="projectId"
        sortable
      />

      <template>
        <!--料号-->
        <el-table-column
          align="center"
          :label="$t('Pool.material')"
          min-width="250px"
          prop="material"
          show-overflow-tooltip
          sortable
        />
        <!--料件描述-->
        <el-table-column
          align="center"
          :label="$t('Pool.materialDescription')"
          min-width="250px"
          prop="materialDescription"
          show-overflow-tooltip
          sortable
        />

        <!--料件分组-->
        <el-table-column
          align="center"
          :label="$t('Pool.materialGroup')"
          min-width="200px"
          prop="materialGroup"
          sortable
        />

        <!--Source Type-->
        <el-table-column
          align="center"
          :label="$t('Pool.sourceType')"
          min-width="200px"
          prop="sourceType"
          sortable
        />

        <!--Tower-->
        <el-table-column
          align="center"
          :label="$t('Pool.tower')"
          min-width="200px"
          prop="tower"
          sortable
        />

        <!--系统价格-->
        <el-table-column
          align="center"
          :label="$t('Pool.pir')"
          min-width="200px"
          prop="pir"
          sortable
        />
      </template>

      <!-- 右浮动 -->
      <template slot="end">
        <!--操作列-->
        <el-table-column
          align="center"
          fixed="right"
          :label="$t('table.operate')"
          min-width="180px"
        >
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="rowEdit(scope.$index, scope.row)">
              <i class="el-icon-edit el-icon--right"></i>
              {{ $t('button.edit') }}
            </el-button>
            <el-button size="mini" type="text" @click="rowDelete(scope.$index, scope.row)">
              <i class="el-icon-delete el-icon--right"></i>
              {{ $t('button.delete') }}
            </el-button>
          </template>
        </el-table-column>
      </template>
    </BaseTable>

    <!--新增对话框-->
    <BaseDialog
      v-if="addDialogVisible"
      :title="$t('dialog.add')"
      :visible.sync="addDialogVisible"
      width="60%"
    >
      <SsAdd :projectList="projectList" @cancel="addDialogVisible = false" @save="afterAddSave" />
    </BaseDialog>

    <!--编辑对话框-->
    <BaseDialog
      v-if="editDialogVisible"
      :title="$t('dialog.edit')"
      :visible.sync="editDialogVisible"
      width="60%"
    >
      <SsEdit
        :input-data="currentEditRow"
        :projectList="projectList"
        @cancel="editDialogVisible = false"
        @save="afterEditSave"
      />
    </BaseDialog>
  </BaseWrap>
</template>

<script>
import { ssPollPricePageList, ssPollPriceDelete, ssPollPriceBatchAdd } from '@/api/pool/ss'
import { fileEexportSsPool } from '@/api/quote/file-export'
import { projectSimpleList } from '@/api/quote/project'
import SsAdd from './components/SsAdd'
import SsEdit from './components/SsEdit'
import XLSX from 'xlsx'

export default {
  name: 'SsCostPool',
  components: { SsAdd, SsEdit },
  props: {},
  data() {
    return {
      // 正在查询
      isRequesting: false,
      // 高级查询选项抽屉弹出标识
      advanceOptionDrawer: false,
      // 页码
      pageNumber: 1,
      // 页展示行数
      pageSize: 10,
      // 总行数
      total: 0,
      // 表格数据
      tableData: [],
      // 查询表单对象
      queryForm: {},
      // 新增对话框可见标识
      addDialogVisible: false,
      // 编辑对话框可见标识
      editDialogVisible: false,
      // 当前编辑行的数据
      currentEditRow: {},
      // filerReader 对象
      reader: null,
      // 当前input框event事件
      currentEvent: '',
      // 专案列表
      projectList: []
    }
  },
  created() {
    this.reader = new FileReader()
    this.reader.onload = async e => {
      this.isRequesting = true
      const data = e.target.result
      const workbook = XLSX.read(data, { type: 'array' })
      const sheetName1 = workbook.SheetNames[0] // 基础数据
      const sheetName2 = workbook.SheetNames[1] // 配置数据
      const baseSheet = workbook.Sheets[sheetName1]
      const configSheet = workbook.Sheets[sheetName2]
      const baeSheetList = XLSX.utils.sheet_to_json(baseSheet)
      const configSheetList = XLSX.utils.sheet_to_json(configSheet)
      const result = this.filterData(baeSheetList, configSheetList)
      try {
        await ssPollPriceBatchAdd(result, { msgSuccess: true, msgError: true })
        this.query()
      } catch (error) {
        console.log(error)
      } finally {
        this.isRequesting = false
        this.currentEvent.target.value = ''
      }
    }
    this.pageDataInit()
  },
  methods: {
    /* 页面数据初始化*/
    pageDataInit() {
      this.query()
      this.getProjectList()
    },
    /* 查询表格数据*/
    async query() {
      try {
        this.isRequesting = true
        this.advanceOptionDrawer = false
        const res = await ssPollPricePageList({
          pageSize: this.pageSize,
          pageNumber: this.pageNumber,
          pageCondition: this.queryForm
        })
        this.tableData = res.data.list
        this.total = res.data.total
      } catch (error) {
        console.log(error)
      } finally {
        this.isRequesting = false
      }
    },
    /* 行记录编辑*/
    rowEdit(index, row) {
      this.currentEditRow = row
      this.editDialogVisible = true
    },
    /* 行记录删除 */
    async rowDelete(index, row) {
      try {
        await this.$confirmBox(this.$t('button.delete'), 'error')
        this.isRequesting = true
        await ssPollPriceDelete({ material: row.material, projectId: row.projectId })
        this.query()
      } catch (error) {
        console.log(error)
      } finally {
        this.isRequesting = false
      }
    },
    // 新增保存之后
    afterAddSave() {
      this.addDialogVisible = false
      this.query()
    },
    // 修改保存之后
    afterEditSave() {
      this.editDialogVisible = false
      this.query()
    },
    // 下载
    async rowDown(index, row) {
      try {
        await this.$confirmBox(this.$t('button.down'), 'success')
        this.isRequesting = true
        const res = await fileEexportSsPool(
          {},
          { downExcelFile: true, msgSuccess: true, msgError: true }
        )
        await this.$downFile(res)
      } catch (error) {
        console.log(error)
      } finally {
        this.isRequesting = false
      }
    },
    uploadFile() {
      this.$refs['inputfile'].click()
    },
    inputfileChange(event) {
      this.currentEvent = event
      const files = event.target.files
      if (!files) return
      var f = files[0]
      this.reader.readAsArrayBuffer(f)
    },
    getConfigModel(configSheetList) {
      const configModel = {}
      for (const item of configSheetList) {
        configModel[item.lableName] = item.propName
      }
      return configModel
    },
    filterData(baeSheetList, configSheetList) {
      const configModel = this.getConfigModel(configSheetList)
      const newBaeSheetList = []
      for (const item of baeSheetList) {
        const newItem = {}
        for (const key in item) {
          newItem[configModel[key]] = item[key]
        }
        newBaeSheetList.push(newItem)
      }
      return newBaeSheetList
    },
    /** 加载专案 */
    async getProjectList() {
      try {
        const res = await projectSimpleList({})
        this.projectList = res.data
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.upload {
  display: none;
}
</style>
